<template>
  <div class="uedit">
    <h1>{{ id ? "编辑" : "创建" }}用户</h1>

    <!-- model绑定表单模型 rules绑定表单验证规则 ref返回表单 -->
    <el-form
      label-position="top"
      :model="model"
      ref="ruleForm"
      @submit.native.prevent
    >
      <!-- prop 接受子组件 name值  validate-event绑定提交时验证-->
      <el-form-item
        prop="email"
        label="邮箱"
        :rules="[
          {
            required: true,
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change'],
          },
        ]"
      >
        <el-input placeholder="请确认邮箱正确" v-model="model.email" />
      </el-form-item>
      <el-form-item
        prop="password"
        label="密码"
        :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]"
      >
        <el-input
          show-password
          placeholder="输入密码"
          v-model="model.password"
        />
      </el-form-item>
      <el-form-item
        prop="nick"
        label="昵称"
        :rules="[
          {
            max: 14,
            message: '最长14字符',
            trigger: ['blur', 'change'],
          },
        ]"
      >
        <el-input placeholder="最长14字符" v-model="model.nick" />
      </el-form-item>
      <el-form-item prop="sex" label="性别">
        <el-select v-model="model.sex">
          <el-option label="男" :value="0"></el-option>
          <el-option label="女" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="headUrl" label="头像" label-width="130px">
        <!-- div 包裹点击弹窗出现 -->
        <div @click="dialogVisible = true" style="width:130px">
          <el-upload
            disabled
            class="avatar-uploader"
            action
            :auto-upload="false"
            :show-file-list="false"
          >
            <img v-if="model.headUrl" :src="model.headUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item
        prop="sign"
        label="签名"
        :rules="[
          {
            max: 40,
            message: '最长40字符',
            trigger: 'change',
          },
        ]"
      >
        <el-input placeholder="最长40字符" v-model="model.sign" />
      </el-form-item>

      <el-form-item>
        <!-- 提交时传入表单 -->
        <el-button
          type="primary"
          native-type="submit"
          @click="save('ruleForm')"
        >
          <span>保存</span>
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 头像弹窗 -->
    <el-dialog
      title="头像剪辑"
      :visible.sync="dialogVisible"
      width="31rem"
      top="2rem"
    >
      <el-upload
        class="avatar-uploader"
        drag
        action
        accept="image/*"
        :show-file-list="false"
        :auto-upload="false"
        :on-change="changeUpload"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          只能上传jpg/png文件，且不超过500kb
        </div>
      </el-upload>
      <div class="cropper-content" style="flex:1">
        <div
          class="show-preview"
          :style="{
            width: previews.w + 'px',
            height: previews.h + 'px',
            overflow: 'hidden',
            margin: '1rem auto',
          }"
        >
          <div :style="previews.div" class="preview">
            <img :src="previews.url" :style="previews.img" />
          </div>
        </div>
        <div class="cropper" style="text-align:center">
          <vueCropper
            ref="cropper"
            :img="option.img"
            :info="option.info"
            :outputSize="option.outputSize"
            :outputType="option.outputType"
            :canScale="option.canScale"
            :autoCrop="option.autoCrop"
            :autoCropWidth="option.autoCropWidth"
            :autoCropHeight="option.autoCropHeight"
            :fixedBox="option.fixedBox"
            :centerBox="option.centerBox"
            @realTime="realTime"
          ></vueCropper>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="fileUpload">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { VueCropper } from "vue-cropper"
import { v1 } from "uuid"
export default {
  components: {
    VueCropper,
  },
  // 路由解耦，注入子组件参数
  props: {
    id: {},
  },
  data() {
    return {
      //头像剪切设置
      previews: {},
      option: {
        img: "", // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 1, // 裁剪生成图片的质量
        outputType: "webp", // 裁剪生成图片的格式
        canScale: true, // 图片是否允许滚轮缩放
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 128, // 默认生成截图框宽度
        autoCropHeight: 128, // 默认生成截图框高度
        fixedBox: true, // 固定截图框大小 不允许改变
        centerBox: true, // 截图框是否被限制在图片里面
      },
      fileName: "",
      //默认隐藏弹窗
      dialogVisible: false,
      //数据模型model
      model: {},
      //上传文件名
      dataName: "",
    }
  },
  methods: {
    //图片修改
    changeUpload(file) {
      this.fileName = file.name
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message("上传文件大小不能超过 5MB!")
        return false
      }
      // 上传成功后将图片地址赋值给裁剪框显示图片 静态文件目录
      this.$nextTick(() => {
        this.option.img = URL.createObjectURL(file.raw)
      })
    },
    //实时预览截图
    realTime(data) {
      this.previews = data
    },
    //确认上传
    fileUpload() {
      this.$refs.cropper.getCropBlob(async (data) => {
        let frm = new FormData()
        //加入数据
        frm.append("avatar", data)
        console.log(frm)
        //随机上传文件名
        this.dataName = v1()
        //加入文件名属性
        frm.append("name", this.dataName)
        //上传数据库
        let res = await this.$http.post("/upload", frm)
        this.model.headUrl = res.data.url

        this.dialogVisible = false
      })
    },

    //上传
    /*     afgerUpload(res) {
      this.model.headUrl = res.url
    }, */
    /*     beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!")
      }
      //文件名处理
      this.dataname.name = v1()
      return isLt2M
    }, */
    //保存或修改
    save(formName) {
      // validate 验证表单返回值
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let res
          if (this.id) {
            //发送数据库修改put请求
            res = await this.$http.put("rest/users", this.model)
          } else {
            //发送数据库创建post请求
            res = await this.$http.post("rest/users", this.model)
          }

          // 判断是否已存在
          if (res.data.name != "MongoError") {
            //创建完成 跳转至列表
            this.$router.push("/users/list")
            //创建消息提醒
            this.$notify({
              title: "成功",
              position: "top-left",
              type: "success",
              message: "用户保存成功！",
            })
          } else {
            this.$notify({
              title: "警告",
              position: "top-left",
              type: "warning",
              message: "邮箱已存在！",
            })
          }
        }
      })
    },
    async fetch() {
      const res = await this.$http.get(`rest/users/${this.id}`)
      this.model = res.data
    },
  },
  created() {
    this.id && this.fetch()
  },
  beforeRouteLeave(to, from, next) {
    //离开时清空组件数据
    this.model = {}
    next()
  },
}
</script>
<style>
.uedit .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.uedit .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.uedit .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px !important;
  text-align: center;
}
.uedit .avatar {
  width: 128px;
  height: 128px;
  display: block;
}

.uedit .cropper {
  width: 28rem;
  height: 21rem;
}
</style>
